package mrh.niubi.librarysystem.controller;

import mrh.niubi.librarysystem.common.Result;
import mrh.niubi.librarysystem.constants.Constants;
import mrh.niubi.librarysystem.pojo.Borrower;
import mrh.niubi.librarysystem.pojo.UserBean;
import mrh.niubi.librarysystem.service.BorrowerService;
import mrh.niubi.librarysystem.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/borrower")
@CrossOrigin(origins = "*")
public class BorrowerApplication {

    @Autowired
    private BorrowerService borrowerService;
    @Autowired
    private UserService userService;

    @GetMapping("/selectBorrowersByQueryinf")
    public Result selectBorrowersByQueryinf (@RequestParam String queryinf)  {
        return Result.success(borrowerService.selectBorrowersByQueryinf(queryinf));
    }

    @GetMapping("/delBorrowersByUsername")
    public Result delBorrowersByUsername (@RequestParam String username) {
        if(borrowerService.delBorrowerByUsername(username) ==1 && userService.delUserByUsername(username)  ==1 ){
            return Result.success();
        }
        else {
            return Result.error(Constants.CODE_500,"服务器删除失败");
        }
    }

    @GetMapping("/addBorrowers")
    public Result addBorrowers (@RequestParam String username,@RequestParam String password,@RequestParam String nickName) {
        UserBean newuser = new UserBean(username,1L,password);
        Borrower newborrower = new Borrower(username,nickName);
        if(borrowerService.addBorrowers(newborrower) ==1 && userService.insertUser(newuser)  ==1 ){
            return Result.success();
        }
        else {
            return Result.error(Constants.CODE_500,"服务器添加失败");
        }
    }

    @GetMapping("/editBorrowers")
    public Result editBorrowers (@RequestParam String username,@RequestParam String password,@RequestParam String nickName) {
        UserBean upuser = new UserBean();
        upuser.setUsername(username);
        upuser.setPassword(password);
        Borrower upborrower = new Borrower(username,nickName );
        if(borrowerService.editBorrowers(upborrower) ==1 && userService.editUser(upuser) ==1 ){
            return Result.success();
        }
        else {
            return Result.error(Constants.CODE_500,"服务器修改失败");
        }
    }

}
